
package com.yang.job;

import com.yang.service.GenerateAudioService;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 音频生成定时任务
 * 作者： yang
 * 时间： 2025/07/08
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GenerateAudioJob {

    private final GenerateAudioService generateAudioService;

    private final AtomicBoolean jobRunning = new AtomicBoolean(true);

    @Value("${digital-human.generate-audio-job.enabled:true}")
    private boolean enabled;

    @PostConstruct
    public void init() {
        if (this.jobRunning.get() && BooleanUtils.isFalse(this.enabled)) {
            this.jobRunning.compareAndSet(true, false);
            log.info("Generate audio job closed.");
        }
    }

    @Scheduled(fixedDelayString = "${digital-human.generate-audio-job.delay:10000}")
    public void schedule() {
        if (!this.jobRunning.get()) {
            return;
        }
        this.execute();
    }

    private void execute() {
        try {
            log.info("执行音频生成定时任务开始");
            generateAudioService.executeAudioGenerationTasks();
            log.info("执行音频生成定时任务完成");
        } catch (Exception e) {
            log.error("执行音频生成定时任务失败", e);
        }
    }
}